<template>
  <div class="content-start-exam">
    <div class="header">
      <!-- <el-button type="success" size="mini" style="float: right" @click="over()"
        >交卷</el-button
      > -->
      <!-- 交卷按钮，弹出提示框输入学生姓名 -->
      <el-button @click="open" size="mini" style="float: right" type="primary">交卷</el-button>

      <p class="right">
        距离考试结束还有：
        <span :class="{ 'time-tip': emergency }">{{ examRestTimeText }}</span>
      </p>
    </div>
    <el-tabs :tab-position="tabPosition" style="height: 90%">
      <el-tab-pane label="单选题">
        <span slot="label">
          <span class="span-box">
            <el-tooltip>
              <i class="el-icon-circle-check"></i>
            </el-tooltip>
            <span>&ensp;单 选 题&emsp;</span>
          </span>
        </span>
        <div class="container" v-for="(item, index) in singleList" :key="item.questionId">
          <TapRadio :index="index" :item="item" :type="'singal'" @radioChildEvent="getSingalAnswer"></TapRadio>
        </div>
      </el-tab-pane>
      <el-tab-pane label="多 选 题">
        <span slot="label">
          <span class="span-box">
            <el-tooltip>
              <i class="el-icon-finished"></i>
            </el-tooltip>
            <span>&ensp;多 选 题&emsp;</span>
          </span>
        </span>
        <div class="container" v-for="(item, index) in multipleList" :key="item.questionId">
          <MultiCheck :no="index + 1" :question="item" @childEvent="getSonEvent"></MultiCheck>
        </div>
      </el-tab-pane>
      <el-tab-pane label="判 断 题">
        <span slot="label">
          <span class="span-box">
            <el-tooltip>
              <i class="el-icon-check"></i>
            </el-tooltip>
            <span>&ensp;判 断 题&emsp;</span>
          </span>
        </span>
        <div class="container" v-for="(item, index) in judgeList" :key="index">
          <TapRadio :index="index" :item="item" :type="'judge'" @radioChildEvent="getJudgeAnswer"></TapRadio>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 是否开始答题提示框 -->
    <div class="begin-mask" v-if="maskVisible">
      <h2>是否开始答题？</h2>
      <div class="info">
        <span><strong>试题：</strong>{{ $route.params.examDescription }}</span><span
          style="margin-left: 30px"><strong>时长：</strong>{{ $route.params.examTimeLimit }}&nbsp;分钟</span>
      </div>
      <div class="ctrl">
        <el-button @click="$router.push({ name: 'examlist' })" size="small" type="info">取消</el-button>
        <el-button @click="handleBeginExam" size="small" type="primary">确定</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import allApis from "@/request";
import MultiCheck from '@/component/MultiCheck.vue';
import TapRadio from "@/component/TapRadio.vue";
import moment from 'moment';
export default {
  components: { MultiCheck, TapRadio },
  name: "beginExam",
  props: ["timelong", "subject"],
  mounted() {
    /**
     * 初始化 this.multipleanser 
     * @params questionsArr 是指所有存储多选题的变量
     */
    for (let i = 0; i < this.multipleList.length; i++) {
      const temp = {
        no: i + 1,
        answer: []
      }
      this.multipleanswer.push(temp)
    }
  },
  data() {
    return {
      // 考试开始时间
      examStartTime: '',

      // 考试总时长
      restTime: 0,

      // 考试时间计时器
      examTimer: null,

      // 是否全屏计时器
      fullscreenTimer: null,

      // 切屏次数
      outNumber: 0,
      tabPosition: "left",

      // 是否开始考试提示信息
      maskVisible: false,
      examTitle: "Java",
      examTime: "90",

      // 考试时间是否进入最后五分钟
      emergency: false,
      examRestTimeText: "",

      // 考试结束弹出框输入个人信息
      // finallVisible: false,

      singleanser: [], //单选答案
      multipleanser: [], //多选答案
      judgeanser: [], //判断答案
      // 单选
      singleList: [],
      //多选
      multipleList: [],
      //判断
      judgeList: [],
      isover: false,

      finalAnswer: [],

      // 考试时要禁用的按键
      disableKeys: [
        "Meta",
        "r",
        "f",
        "c",
        "Control",
        "Alt",
        "Control",
        "Escape",
        "F1",
        "F2",
        "F3",
        "F4",
        "F5",
        "F6",
        "F7",
        "F8",
        "F9",
        "F10",
        "F11",
        // "F12",
      ],
    };
  },

  methods: {
    time() {
      this.examRestTimeText = `${Math.floor(this.restTime / 60)} 分钟`;
      this.examTimer = setInterval(() => {
        this.restTime -= 1;

        if (this.restTime > 300) {
          this.examRestTimeText = `${Math.floor(this.restTime / 60)} 分钟`;
        } else {
          this.emergency = true;
          const m = Math.floor(this.restTime / 60);
          const s = (this.examRestTimeText =
            (m ? ` ${m} 分` : "") + ` ${this.restTime % 60} 秒`);
        }
        if (this.restTime === 0) {
          this.$router.replace("/myexam");
        }
      }, 1000);
    },

    // 考试开始禁用键盘快捷键
    handleDisableKeys(event) {
      if (this.disableKeys.some((item) => item === event.key)) {
        event.preventDefault();
        return false;
      }
    },

    getAllAnswer(answerArr) {
      answerArr?.forEach(item => {
        const temp = {
          questionId: item.questionId,
          answerOptionIds: item.answer
        }
        this.finalAnswer.push(temp)
      })
    },

    // 将每一道多选题的题号以及答案这里到 multipleanser 数组中
    getSonEvent(data) {
      const { questionId, answer } = data
      const temp = this.multipleanser
      let ifAdd = true;
      for (let i = 0; i < temp.length; i++) {
        if (temp[i].questionId === questionId) {
          temp[i].answer = answer
          ifAdd = false
        }
      }
      if (ifAdd) {
        temp.push(data)
      }
      this.multipleanser = temp;
    },


    getSingalAnswer(data) {
      const { no, questionId, answer } = data
      const temp = this.singleanser
      let ifAdd = true;
      for (let i = 0; i < temp.length; i++) {
        if (temp[i].questionId === questionId) {
          temp[i].answer = answer
          ifAdd = false
        }
      }
      if (ifAdd) {
        temp.push(data)
      }
      this.singleanser = temp;
    },

    getJudgeAnswer(data) {
      const { no, questionId, answer } = data
      let temp = this.judgeanser
      let ifAdd = true;
      for (let i = 0; i < temp.length; i++) {
        if (temp[i].questionId === questionId) {
          temp[i].answer = answer
          ifAdd = false
        }
      }
      if (ifAdd) {
        temp.push(data)
      }
      this.judgeanser = temp;
    },

    open() {
      const { submitAnswer } = allApis;

      this.$confirm("确定要交卷吗？, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.getAllAnswer(this.multipleanser);
          this.getAllAnswer(this.singleanser);
          this.getAllAnswer(this.judgeanser);
          const arr = {
            examId: sessionStorage.getItem('examId'),
            userId: sessionStorage.getItem('userId'),
            examJoinDate: this.examStartTime,
            results: this.finalAnswer
          }
          //向后端发送答案
          submitAnswer(arr)
            .then((res) => {
              console.log(res);
              // 判断交卷成功方可进行跳转
              // this.$router.replace({ name: "myexam" });
              // this.$notify({
              //   title: "考试结束",
              //   // message: "考试结束，预祝取得好成绩！",
              // });
            })
            .catch((err) => {
              console.log(err);
              this.$message({
                type: "info",
                message: "交卷失败，请联系监考老师",
              });
            });

          // 为了开发阶段的便利，这里先强行跳转，等和后端接口联调之后，这部分代码记得删除
          this.$router.replace({ name: "myexam" });
          this.$notify({
            title: "考试结束",
            // message: "考试结束，预祝取得好成绩！",
          });
        })
        .catch((err) => {
          console.log(err);
          this.$message({
            type: "info",
            message: "已取消交卷",
          });
        });
    },

    // 保证考试过程中为全屏
    // handleScreenChange(event) {
    //   if (document.fullscreenElement === null) {
    //     document.documentElement.requestFullscreen().catch(() => {});
    //     this.$alert("考试过程中请不要尝试退出全屏", "提示");
    //   }
    // },

    fullScreenDetect() {
      this.fullscreenTimer = setTimeout(() => {
        document.documentElement.focus();

        if (document.fullscreenElement) {
          clearTimeout(this.fullscreenTimer);
        } else {
          document.documentElement.focus();
          document.documentElement.requestFullscreen().catch(() => { });
          this.fullScreenDetect();
        }
      }, 500);
    },

    // 屏幕大小改变时，监测是否为全屏，不是全屏则再次全屏
    hadleScreenResize(event) {
      if (document.fullscreenElement === null) {
        this.fullScreenDetect();
      }
    },

    // 监测学生切屏，如果切屏三次则自动交卷
    handleOnLeaveExam() {
      // this.outNumber++;

      // if (this.outNumber > 2) {
      //   this.$router.replace({ name: "myexam" });
      //   this.$notify({
      //     title: "考试结束提示",
      //     message: "由于你违反考试规则，已强制交卷。",
      //     duration: 0,
      //   });
      // } else {
      //   this.$alert(
      //     `你已经切屏了 ${this.outNumber} 次,超过 3 次自动交卷`,
      //     "警告！",
      //     {
      //       type: "warning",
      //     }
      //   );
      // }
    },

    handleBeginExam() {
      const date = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
      console.log(date);
      this.examStartTime = date;

      this.maskVisible = false;

      this.time();

      // 监测学生切屏，如果切屏三次则自动交卷
      window.addEventListener("blur", this.handleOnLeaveExam);
    },

    // 取消考试
    // cancelExam() {
    //   this.$router.replace({ name: "examlist", params:{flag:true} });
    // },
  },

  created() {
    // 因为多选框绑定要是一个数组 所以根据题目的长度遍历出一个空数组
    // this.multipleList.forEach((x) => this.multipleanser.push([]));
  },

  mounted() {
    console.log(this.$route);

    /* 获取单选题数组 */
    this.singleList = this.$route.params.examQuestion.filter((item) => {
      return item.questionType === "单选题";
    });
    console.log(this.singleList);

    /* 获取多选题数组 */
    this.multipleList = this.$route.params.examQuestion.filter((item) => {
      return item.questionType === "多选题";
    });
    // console.log(this.$route.params.examQuestion[8].questionOptionIds);

    /* 获取判断题数组 */
    this.judgeList = this.$route.params.examQuestion.filter((item) => {
      return item.questionType === "判断题";
    });
    console.log(this.judgeList);
    // 计算考试总时间（秒）
    this.restTime = this.$route.params.examTimeLimit * 60;

    // 刚进入页面提示用户是否要开始答题
    this.maskVisible = true;

    // 关闭导航栏显示
    this.$store.state.examing = true;

    // 获取全屏
    document.documentElement.requestFullscreen().catch((err) => { });

    // 禁用键盘事件
    window.addEventListener("keydown", this.handleDisableKeys);

    // 监测用户退出全屏并提示
    document.addEventListener("fullscreenchange", this.handleScreenChange);
    window.addEventListener("resize", this.hadleScreenResize);
  },

  beforeDestroy() {
    document.exitFullscreen();
    window.removeEventListener("keydown", this.handleDisableKeys);
    document.removeEventListener("fullscreenchange", this.handleScreenChange);
    window.removeEventListener("resize", this.hadleScreenResize);
    window.removeEventListener("blur", this.handleOnLeaveExam);
    clearInterval(this.examTimer);
    this.$store.state.examing = false;
  },
};
</script>

<style lang="scss" scoped>
.content-start-exam {
  .header {
    width: 100%;
    height: 50px;
    font-size: 20px;

    .right {
      width: 40%;
      height: 40px;
      line-height: 25px;
      text-align: right;
      float: right;
      margin: 0;
      margin-right: 60px;
    }
  }

  // 左边菜单栏
  ::v-deep .el-tabs__item {
    height: 100px;
    font-size: 20px;
    width: 30%;
  }

  ::v-deep .el-tabs__content {
    // margin-right: 40px;
    float: left;
    width: 70%;
    height: 100%;
    padding-left: 60px;
    font-size: 20px;
    overflow: auto;

    .container {
      width: 100%;
      height: 100%;
      margin-top: 20px;

      // 单选
      .single {
        width: 100%;
        height: 30px;
        text-align: left;
        line-height: 40px;
        margin: 10px 0;

        .el-radio__label {
          font-size: 18px;
        }
      }

      //多选
      .multiple {
        width: 100%;
        height: 30px;
        text-align: left;
        line-height: 30px;
        margin: 10px 0;

        .el-checkbox__label {
          font-size: 18px;
        }
      }

      //判断
      .judge {
        width: 100%;
        height: 30px;
        text-align: left;
        line-height: 40px;
        margin: 10px 0;

        .el-radio__label {
          font-size: 18px;
        }
      }
    }
  }

  .finall-exam {
    left: 0;
    top: 0;
    height: 200px;
    width: 200px;
  }

  .begin-mask {
    position: fixed;
    width: 100vw;
    height: 100vh;
    left: 0;
    top: 0;
    z-index: 2000;
    background-color: #fff;

    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    h2 {
      margin-top: -15%;
      margin-bottom: 3%;
      font-size: 30px;
      letter-spacing: 10px;
    }

    .info {
      margin-bottom: 3%;
    }
  }

  .begin-mask {
    position: fixed;
    width: 100vw;
    height: 100vh;
    left: 0;
    top: 0;
    z-index: 2000;
    background-color: #fff;

    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    h2 {
      margin-top: -10%;
      margin-bottom: 3%;
      font-size: 30px;
      letter-spacing: 10px;
    }

    .info {
      margin-bottom: 3%;
    }
  }
}
</style>
